/**
 * 心灵氧吧模块入口
 * Created by alice on 2016/7/11.
 */
require.config({
    baseUrl:'../js',
    paths:{
        "getData":"Util/getData",
        "config":"common/config",
        "components":"common/components",
        "common":"common/common",
        "jquery":"lib/jquery.min",
        "weui":"lib/jquery-weui.min",
        "wx":"lib/jweixin-1.0.0"
    },
    shim : {
        "components": { deps : ["jquery"] },
        "weui":{deps:["jquery"]}
    },
    urlArgs: "v=" + (new Date()).getTime()//以禁用浏览器缓存,上线后注释掉
});
require(['jquery','getData','config','common','components','weui','wx'],function($,getData,config,common,components,weui,wx){
    //获取gm obj
    var gm=common.gm;
    var token=gm.para.get(window.location.href,"token");
    if(!gm.common.isObjUsable(token)){
        token='';
    }
    var generatedCount = 1;
    var totalPage=0;
    var pageNum=1;
    var itemIndex=0;

    var status = window.location.hash;
    if(status == "#b"){
        $("div .all h2").addClass("dserfa");
        $(".help h2").removeClass("dserfa");
        $("#tab1").hide();
        $("#tab2").show();
        itemIndex=1;
    }else{
        $("div .all h2").removeClass("dserfa");
        $(".help h2").addClass("dserfa");
        $("#tab2").hide();
        $("#tab1").show();
        itemIndex=0;
    }

    //下拉自动加载数据
    var generatedCount = 1;//页码
    var generatedCount1 = 1;//页码
    //获取到顶顶部的位置
    var ScrollTop0=0;
    var ScrollTop1=0;
    /*$(document).ready(function (){
        var nScrollHight = 0; //滚动距离总长(注意不是滚动条的长度)
        var nScrollTop = 0;   //滚动到的当前位置
        var nDivHight = $("#wrapper").height()+$(".conti").height()+1;
        var isload=0;//防止多次加载
        $("#wrapper").scroll(function(){
            var that=this;
            nScrollHight = $(this)[0].scrollHeight;
            nScrollTop = $(this)[0].scrollTop;
            if(nScrollTop + nDivHight >= nScrollHight){
                if(itemIndex==0){
                    if(isload==0){
                        isload=1;
                        generatedCount++;
                        getData.getJson({
                            page:"content",
                            inter:"getArticleInfoList",
                            data:{token:token,contentType:11,collectRule:1,pageSize:15,pageNum:generatedCount},
                            method:"GET",
                            callback:function(data){
                                if(data.code=="2000"){
                                    if(data.value!=undefined && data.value!=null && data.value.length==0){//无数据时
                                        loadEnd();
                                        isload=1;
                                    }else{
                                        $(".list1").append(getHeartContext(data));
                                        nScrollHight = $(that)[0].scrollHeight;
                                        nScrollTop = $(that)[0].scrollTop;
                                        nDivHight = $("#wrapper").height()+$(".conti").height()+1;
                                        if(nScrollTop+nDivHight<nScrollHight)
                                            isload=1;
                                    }
                                }

                            }
                        });

                    }
                }else if(itemIndex==1){
                    if(isload==0){
                        isload=1;
                        generatedCount1++;
                        getData.getJson({
                            page:"patient",
                            inter:"getPatientCommonVideoList",
                            data:{pageSize:15,pageNum:generatedCount1},
                            method:"GET",
                            callback:function(data){
                                if(data.code=="2000"){
                                    if(data.value!=undefined && data.value!=null && data.value.length==0){//无数据时
                                        loadEnd1();
                                        isload=1;
                                    }else{
                                        $(".list2").append(vedioStr(data));
                                        nScrollHight = $(that)[0].scrollHeight;
                                        nScrollTop = $(that)[0].scrollTop;
                                        nDivHight = $("#wrapper").height()+$(".conti").height()+1;
                                        if(nScrollTop+nDivHight<nScrollHight)
                                            isload=1;
                                    }
                                }

                            }
                        });

                    }
                }
            }else{//恢复加载更多
                isload=0;
            }

        });
    });*/

    if($("#wrapper")[0]){
        $("#tab1,#tab2").infinite(100).on("infinite", function() {
            var self = this;
            if(self.loading) return;
            self.loading = true;
            setTimeout(function() {
                var contentTitle="";
                var _illnessId = $(".illness .lan").length>0?parseInt($(".illness .lan").attr("id")):"";
                if(itemIndex==0){
                    generatedCount++;
                    getData.getJson({
                        page:"content",
                        inter:"getArticleInfoList",
                        data:{token:token,contentType:11,collectRule:1,pageSize:15,pageNum:generatedCount},
                        method:"GET",
                        callback:function(data){
                            if(data.code=="2000"){
                                if(data.value!=undefined && data.value!=null && data.value.length==0){//无数据时
                                    $("#tab1 #infinite_load_doctor").html("没有更多数据了！");
                                    $("#tab1").destroyInfinite();
                                }else{
                                    if(data.value.length<15){
                                        $("#tab1 #infinite_load_doctor").html("没有更多数据了！");
                                        $("#tab1").destroyInfinite();
                                    }
                                    $(".list1").append(getHeartContext(data));

                                }
                            }

                        }
                    });
                }else if(itemIndex==1){
                    generatedCount1++;
                    getData.getJson({
                        page:"patient",
                        inter:"getPatientCommonVideoList",
                        data:{pageSize:15,pageNum:generatedCount1},
                        method:"GET",
                        callback:function(data){
                            if(data.code=="2000"){
                                if(data.value!=undefined && data.value!=null && data.value.length==0){//无数据时
                                    $("#tab2 #infinite_load_doctor1").html("没有更多数据了！");
                                    $("#tab2").destroyInfinite();
                                }else{
                                    if(data.value.length<15){
                                        $("#tab2 #infinite_load_doctor1").html("没有更多数据了！");
                                        $("#tab2").destroyInfinite();
                                    }
                                    $(".list2").append(vedioStr(data));

                                }
                            }

                        }
                    });
                }
                self.loading = false;
            }, 1500);   //模拟延迟
        });
    }

    /**
     * 加载完成
     */
    function loadEnd(){
        console.log("laodend");
        $(".pullUpLabel").html("没有更多信息了！");
    }
    function loadEnd1(){
        console.log("laodend");
        $(".pullUpLabel1").html("没有更多信息了！");
    }

    /**
     * 首次加载视频列表
     */
    window._loading = new components.mask("loading");
    window._loading.show();
    getData.getJson({
        page:"patient",
        inter:"getPatientCommonVideoList",
        data:{pageSize:15,pageNum:1},
        callback:function(data){

            if(data.code="2000"){
                _loading.hide();
                var hasValue=data.value;
                if(hasValue.length>0){
                    $(".list2").html(vedioStr(data));
                    pageNum++;
                }else{

                }
            }
        }
    });
    /**
     * 首次加载健康指导
     */
    getData.getJson({
        page:"content",
        inter:"getArticleInfoList",
        data:{token:token,contentType:11,collectRule:1,pageSize:15,pageNum:1},
        callback:function(data){
            if(data.code="2000"){
                _loading.hide();
                $(".list1").html(getHeartContext(data));
            }
        }
    });



    function Refresh(type) {
        setTimeout(function () {
            var type=type ||$("#wrapper ul").attr("data");
            window._loading = new components.mask("loading");
            window._loading.show();
            if(type==1){
                //调用健康指导
                refreshdata(type,15,1,function(data){
                    _loading.hide();
                    $(".list1").html(getHeartContext(data));
                    generatedCount=1;
                    totalPage=data.total;
                    if(totalPage<=1){
                        if($(".scroller").children().hasClass("pullUp")){
                            $(".pullUp").remove();
                        }
                    }else{
                        if(!$(".scroller").children().hasClass("pullUp"))
                            $(".scroller").append("<div class='pullUp'><div class='loader'><span></span><span></span><span></span><span></span></div><div class='pullUpLabel'>上拉加载 更多...</div></div>");
                    }
                    wrapper.refresh();

                });
            }else if(type==2)
                //调用在线视频
                refreshdata(type,15,1,function(data){
                    _loading.hide();
                    $(".list1").html(vedioStr(data));
                    generatedCount=1;
                    totalPage=data.total;
                    if(totalPage<=1){
                        if($(".scroller").children().hasClass("pullUp")){
                            $(".pullUp").remove();
                        }
                    }else{
                        if(!$(".scroller").children().hasClass("pullUp"))
                            $(".scroller").append("<div class='pullUp'><div class='loader'><span></span><span></span><span></span><span></span></div><div class='pullUpLabel'>上拉加载 更多...</div></div>");
                    }

                    wrapper.refresh();

                });
            //wrapper.refresh();/****remember to refresh after  action completed！ ---yourId.refresh(); ----| ****/
        }, 1000);

    }

    function Load(type) {
        setTimeout(function () {// <-- Simulate network congestion, remove setTimeout from production!
            var type=type ||$("#wrapper ul").attr("data");
            ++generatedCount;
            if(type==1){//健康指导
                if(generatedCount<=totalPage)
                    refreshdata(type,15,generatedCount,function(data){
                        $(".list1").append(getHeartContext(data));
                        if(generatedCount==data.total){
                            console.log($(".scroller").children("div").hasClass("pullUp"));
                            if($(".scroller").children("div").hasClass("pullUp")){
                                $(".pullUp").remove();
                            }
                        }
                        wrapper.refresh();
                    });
                else
                    $(".pullUp").hide();
            }else if(type==2){//在线视频
                if(generatedCount<=totalPage)
                    refreshdata(type,15,generatedCount,function(data){
                        $(".list1").append(vedioStr(data));
                        if(generatedCount==data.total){
                            console.log($(".scroller").children().hasClass("pullUp"));
                            if($(".scroller").children().hasClass("pullUp")){
                                $(".pullUp").remove();
                            }
                        }
                        wrapper.refresh();
                    });
                else
                    $(".pullUp").hide();
            }
            //wrapper.refresh();/****remember to refresh after action completed！！！   ---id.refresh(); --- ****/
        }, 1000);
    }
    /**
     * 心灵氧吧页面加载更多时调用
     * @param page 当前页面有多少条记录
     * @param pageno 当前第几页面
     * @param type 1 健康指导 2 在线视频
     * @param callback
     */
    function refreshdata(type,page,pageno,callbak){
        if(type==1)
            getData.getJson({
                page:"content",
                inter:"getArticleInfoList",
                data:{token:token,contentType:11,collectRule:1,pageSize:page,pageNum:pageno},
                callback:function(data){
                    if(data.code="2000")
                        callbak && callbak(data);
                }
            });
        else if(type==2)
            getData.getJson({
                page:"patient",
                inter:"getPatientCommonVideoList",
                data:{pageSize:page,pageNum:pageno},
                callback:function(data){
                    if(data.code="2000")
                        callbak && callbak(data);
                }
            });
    }
//分页功能结束




    //健康指导的回调
    function getHeartContext(data){
        var arr = [];
        var tmp='<li favoriteUuid="{favoriteUuid}" contentUuid="{uuid}" favoriteType="{favoriteUuid}" value="{url}">\
                    <a href="{url}">\
                        <div class="asbg" data-box-status="0" style="transition: all 0.1s ease; transform: translate3d(0rem, 0px, 0px);">\
                            <div class="live">\
                                <img src="{imageUrl}">\
                            </div>\
                            <div class="text">\
                                <div class="collectionContentTitle"><p>{author}{contentTitle}</p></div>\
                                <p class="time">\
                                    {collectNum}{readNum}\
                                </p>\
                            </div>\
                        </div>\
                    </a>\
				</li>';
        var defimg='../imgs/spimg.png';
        $(data.value).each(function(i,o){
            //是否收藏
            var isCollection=o["collect"] == true?1:0;
            var title= o.contentTitle;
            var desc= o.contentTitle;
            var getimg=gm.common.isObjUsable(o.imageUrl)?window._interfaceImgPath+""+o.imageUrl:defimg;
            o.imageUrl=getimg;//
            var img= "group1"+getimg.split('group1')[1];
            var favoriteType=0;
            var contentUuid= o.id;
            //collectRule 表示 患者
            var str="isCollection="+isCollection+"&title="+title+"&desc="+desc+"&img="+img+"&contentType="+favoriteType+"&favoriteUuid="+contentUuid+"&collectRule=1&token="+token;


            o.url=window._interfacePath+"/hxq/doctor/informationfordetails.html?client=ios&"+str;
            var collectNum=gm.common.isObjUsable(o.collectNum);
            o.collectNum=collectNum?"<span style='margin-right: .5rem;'>收藏 "+o.collectNum+"</span>":"<span style='margin-right: .5rem;'>收藏 0</span>";//判断收藏字段是否存在
            var readNum=o.readNum;
            if(!gm.common.isObjUsable(readNum))
                o.readNum="<span style='margin-right:.5rem;'>阅读 0</span>";
            else
                o.readNum="<span style='margin-right:.5rem;'>阅读 "+readNum+"</span>";

            arr.push(gm.replace(tmp,o));
        });
        return arr;
    }

    //获取视频信息
    function getVideos(){
        window._loading = new components.mask("loading");
        window._loading.show();
        //获取在线视频
        getData.getJson({
            page:"patient",
            inter:"getPatientCommonVideoList",
            data:{pageNum:1,pageSize:20},
            loading:true,
            callback:function(_data){
                if(_data.code=="2000")
                    getVideoslist(_data);
            }
        });
    }
    //在线视频回调
    function getVideoslist(data){
        //服务器传输回应
        if(!data){
            $.alert("服务器出错!");
        }
        if(data.code==200){
            var arr = [];
            var _p = "";
//			<p class="care">{collectNum}</p>\

            $(".list1").html(vedioStr(data).join("")).children("li").ontouch(function(){
                var geturl=$(this).attr("value");
                if(geturl!=undefined && geturl!=null && geturl!="")
                    gm.pul.toUrl(geturl);
            },true);
        }else{
            $.alert(data.message);
        }
    }

    /**
     * 在线视频str拼接
     */
    function vedioStr(data){
        var arr = [];
        var tmp='<li contextuuid="{uuid}" favoriteuuid="{favoriteUuid}" value="{url}">\
                    <a href="{url}">\
                    <div class="asbg">\
                        <div class="live">\
                            <img src="{image}">\
                        </div>\
                        <div class="text">\
                            <div class="collectionContentTitle">\
                                <p>{userName}-{videoName}</p>\
                            </div>\
                            <p class="time">\
                                {commentNumber}{collNumber}\
                            </p>\
                        </div>\
                        </div>\
                        </a>\
                      </li>';

        $(data.value).each(function(i,o){
            //是否收藏
            var isCollection=o["isCollect"] ==1?1:0;
            var title= o.videoName;
            var desc= o.videoIntroduction;

            o.image=gm.common.isObjUsable(o.image)?window._interfaceImgPath+""+o.image:window.___defaultImage;
            var img="group1"+o.image.split('group1')[1];//"group1"+o.imgUrl.split('group1')[1];
            var favoriteUuid= o.id;
            //患者端collectRule=1;
            //var userid= o.
            var str="isCollection="+isCollection+"&title="+title+"&desc="+desc+"&img="+img+"&token="+token+"&favoriteUuid="+favoriteUuid+"&contentType=1";
            o.url=window._interfacePath+"/hxq/patient/playing.html?client=ios&"+str;



            var collectNum=gm.common.isObjUsable(o.collNumber);
            o.collNumber=collectNum?"<span style='margin-right: .5rem;'>收藏 "+o.collNumber+"</span>":"<span style='margin-right: .5rem;'>收藏 0</span>";//判断收藏字段是否存在
            var commonNum=gm.common.isObjUsable(o.commentNumber);
            o.commentNumber=commonNum?"<span style='margin-right: .5rem;'>评论 "+o.commentNumber+"</span>":"<span style='margin-right: .5rem;'>评论 0</span>";//判断评论字段是否存在
            arr.push(gm.replace(tmp,o));
        });
        return arr;
    }

    // 列表切换
    $(".conti div").bind({
        touchend:function(){
            $(".conti div h2").removeClass("dserfa");
            $(this).find("h2").addClass("dserfa");

            var _s = $(".conti .help").find("h2").hasClass("dserfa");
            if (!_s) {
                window.location.hash = "#b";
                //$("#wrapper ul").attr("data","2");
                $("#tab1").hide();
                $("#tab2").show();
                itemIndex=1;
            }else{
                window.location.hash = "#a";
                //$("#wrapper ul").attr("data","1");
                $("#tab2").hide();
                $("#tab1").show();
                itemIndex=0;
            }
        }
    });

    //收藏
    $(".alllive ul").on("touchend",".icon-greystars,.icon-redstars",function(){
        var _o = $(this).hasClass("icon-redstars");
        if (_o) {
            $(this).attr("class","icon-greystars");
            //$(this).siblings().attr("class","pts-greencollection");
            var _p = $(this).parents("li").attr("favoriteUuid");
            //$(this).find("p").hide();
            //var _k = $(this).find("p").attr("foucsNum");
            //$(this).find("p").html(parseInt(_k));

            getData.getJson({
                page:"doctor",
                inter:"delFavorite",
                data:{favoriteUuid:_p},
                callback:function(data){
                    //服务器传输回应
                    if(!data){
                        components.alert("服务器出错!");
                    }
                    if(data.query.success=="1"){
                        console.log("删除成功!");
                    }else{
                        components.alert(data.query.message);
                    }
                }
            });
        }else{
            $(this).attr("class","icon-redstars");
            var _p = $(this).parents("li").attr("contextUuid");
            var _k = $(this);
            var _f = $(this).parents("ul").attr("class");
            _f = _f.substr(_f.length-1,1);
            $(this).find("p").show();
            //var _s = _k.find("p").text();
            //_k.find("p").html(parseInt(_s)+1);
            getData.getJson({
                page:"patient",
                inter:"addFavorite",
                data:{customerUuid:gm.patient.getPatient(),newsid:_p,favoriteType:_f},
                callback:function(data){
                    //服务器传输回应
                    if(!data){
                        components.alert("服务器出错!");
                    }
                    if(data.query.success=="1"){
                        // $(this).attr("favoriteUuid",data.favoriteUuid);
                        _k.parents("li").attr("favoriteUuid",data.favoriteUuid);
                    }else{
                        components.alert(data.query.message);
                    }
                }
            });
        }
    });

    //给心灵氧吧文章绑定收藏和分享 的方法
    $.fn.collectShare = function(){
        var _  = this;
        //收藏
        _.find("i.icon-redstars,i.icon-greystars").ontouch(function(){
            var _this = this;
            var _class = $(this).attr("class");
            var _newsid = $(this).parent().parent().attr("contextuuid");
            var _count= parseInt($(_this).children(".care").html());//当前收藏量
            if(_class == "icon-redstars"){//已收藏
                _class = "icon-greystars";
                var _favid = $(this).parent().parent().attr("favoriteuuid");
                //删除收藏
                gm.common.delFavorites(_favid,function(data){
                    if(data.query.success=="1"){
                        $(_this).parent().parent().removeAttr("favoriteuuid");
                        $(_this).children(".care").html(--_count);
                    }
                });
            }else{//未收藏
                _class = "icon-redstars";
                //获取文章类型
                var getContentType=$(this).parent().parent().parent().attr("data");
                //添加收藏
                gm.patient.addFavorite(_newsid,getContentType,function(data){
                    $(_this).parent().parent().attr("favoriteuuid",data.favoriteUuid);
                    $(_this).children(".care").html(++_count);
                });
            }
            $(this).attr("class",_class);//改变收藏状态
        },true);

        //分享
        _.find("i.pts-greencollection,i.icon-mycollectiongray").ontouch(function(){

            var _ = $(this);
            var _contentUuid = $(this).parent().parent().attr("contextuuid");

            if (!_contentUuid) {
                _contentUuid = $(this).parents("dd").attr("contentuuid");
            }
            var p = _.parent();
            var _title=p.siblings(".asbg").find(".text h2").html();
            var state=p.parent().parent().attr("data");
            var _link="";
            if(state=="1"){//表示 文章
                _link=window._interfacePath + "../doctor/informationfordetails.html?contentUuid=" + _contentUuid;
            }else if(state=="2"){//表示 视频
                _link=window._interfacePath + "playing.html?vidoUuid=" + _contentUuid;
            }

            var obj = {
                "title":_title,
                "desc":_title,
                "img":p.siblings(".scvideo img").attr("src"),
                "link":_link
            };

            gm.share(obj,function(){
                /*$.getDate({
                 page:"doctor",
                 inter:"addDoctorShare",
                 data:{contentUuid:_contentUuid,doctorUuid:gm.user.getDoctor()},
                 callback:function(data){
                 _czc.push(["_trackEvent","阅读","分享","",'','addDoctorShare']);
                 }
                 });*/
            });
        },true);

        return _;
    };

    //给心灵氧吧视频绑定收藏和分享 的方法
    $.fn.VedioCollectShare = function(){
        var _  = this;
        //收藏
        _.find("i.icon-redstars,i.icon-greystars").ontouch(function(){
            var _this = this;
            var _class = $(this).attr("class");
            var _newsid = $(this).parent().parent().attr("contextuuid");
            var _count= parseInt($(_this).parent().parent().find("a").children(".text").children(".time").find("span").eq(1).html());//当前收藏量
            if(_class == "icon-redstars"){//已收藏
                _class = "icon-greystars";
                var _favid = $(this).parent().parent().attr("favoriteuuid");
                //删除收藏
                gm.user.delFavorites(_favid,function(data){
                    if(data.query.success=="1"){
                        $(_this).parent().parent().removeAttr("favoriteuuid");
                        $(_this).parent().parent().find("a").children(".text").children(".time").find("span").eq(1).html(--_count);
                    }
                });
            }else{//未收藏
                _class = "icon-redstars";
                //获取文章类型
                var getContentType=$(this).parent().parent().parent().attr("data");
                //添加收藏
                gm.patient.addFavorite(_newsid,getContentType,function(data){
                    $(_this).parent().parent().attr("favoriteuuid",data.favoriteUuid);
                    $(_this).parent().parent().find("a").children(".text").children(".time").find("span").eq(1).html(++_count);
                });
            }
            $(this).attr("class",_class);//改变收藏状态
        },true);

        //分享
        _.find("i.pts-greencollection,i.icon-mycollection").ontouch(function(){

            var _ = $(this);
            var _contentUuid = $(this).parent().parent().attr("contextuuid");

            if (!_contentUuid) {
                _contentUuid = $(this).parents("dd").attr("contentuuid");
            }
            var p = _.parent();
            var _title=p.parent().find("a").find(".text p").eq(0).html();
            var state=p.parent().parent().attr("data");
            var _link="";
            var _img=p.siblings("a").find(".live img").attr("src");
            if(state=="1"){//表示 文章
                _link=window._interfacePath + "/html/thedoctorinformation/informationfordetails.shtml?contentUuid=" + p.attr("contextuuid");
            }else if(state=="2"){//表示 视频
                _link=window._interfacePath + "/html/lecture/playing.shtml?vidoUuid=" + _contentUuid;
            }

            var obj = {
                "title":_title,
                "desc":_title,
                "img":_img,
                "link":_link
            };

            gm.share(obj,function(){
                /*$.getDate({
                 page:"doctor",
                 inter:"addDoctorShare",
                 data:{contentUuid:_contentUuid,doctorUuid:gm.user.getDoctor()},
                 callback:function(data){
                 _czc.push(["_trackEvent","阅读","分享","",'','addDoctorShare']);
                 }
                 });*/
            });
        },true);

        return _;
    };
    setTimeout(function(){gm.common.setTitle(document.title);},200);

});
